package com.fuqi.android.zhongcai.business.shuig.view.activity;


import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.fuqi.android.zhongcai.R;
import com.fuqi.android.zhongcai.base.request.api.PushImgApi;
import com.fuqi.android.zhongcai.base.request.result.PushResult;
import com.fuqi.android.zhongcai.base.view.activity.BaseActivity;
import com.fuqi.android.zhongcai.base.view.widget.CustomProgress;
import com.fuqi.android.zhongcai.business.shuig.request.api.SaveCommentApi;
import com.fuqi.android.zhongcai.business.shuig.request.result.SaveCommentResult;
import com.fuqi.android.zhongcai.business.shuig.view.widget.CJRow.ARResponse;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.FileUtil;
import com.fuqi.android.zhongcai.utils.ImageUtils;
import com.fuqi.android.zhongcai.utils.RegexUtil;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.fuqi.framework.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class ShuiGCommentActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,BGASortableNinePhotoLayout.Delegate {
    @Bind(R.id.ratingbar_skill)
    RatingBar mRbskill;
    @Bind(R.id.ratingbar_service)
    RatingBar mRbservice;
    @Bind(R.id.ratingbar_speed)
    RatingBar mRbspeed;
    @Bind(R.id.activity_discover_invest_publish_picture_iv)
    ImageView mIvPub;
    @Bind(R.id.et_remark)
    EditText mEtRemark;

    ARResponse response;

    private BGASortableNinePhotoLayout ninePhotoLayout;
    //    选择头像请求码
    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;
//    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private static final int MAX_PHOTO_COUNT = 9;
    private ArrayList<String> netPhotos = new ArrayList<>();

    @OnClick({R.id.btn_submit,R.id.activity_discover_invest_publish_picture_iv})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.activity_discover_invest_publish_picture_iv:
                choicePhotoWrapper();
                break;
            case R.id.btn_submit:
                netPhotos = ninePhotoLayout.getData();
                if(mRbskill.getRating() == 0 || mRbservice.getRating() == 0 || mRbspeed.getRating() == 0){
                    ActivityUtils.toast("请评价。");
                    return;
                }else if(!RegexUtil.checkNotNull(mEtRemark.getText().toString())){
                    ActivityUtils.toast("请输入评论。");
                    return;
                }else if(netPhotos.size() == 0){
                    ActivityUtils.toast("请上传图片。");
                    return;
                }

                doUpload();
                break;
        }
    }

    Response.Listener<SaveCommentResult> respOrderHandleListener = new Response.Listener<SaveCommentResult>() {

        @Override
        public void onResponse(SaveCommentResult response) {
            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast("评论提交成功。");
                finish();
                Log.i("juner", "juner respOrderHandleListener response : ");
            } else {
            }
        }
    };

    Response.Listener<PushResult> respWorkersListener = new Response.Listener<PushResult>() {

        @Override
        public void onResponse(PushResult response) {
            CustomProgress.close();
            FileUtil.clearDir(FileUtil.getTempFile());
            if (HandleCode.requestSuccess()) {
                netPhotos.addAll(StringUtil.getList(response.getPath(),","));
//                if(netPhotos.size() == selectedPhotos.size()) {
                    doPublish();
//                }
                Log.i("juner", "juner respWorkersListener response : " + response.getPath());
            } else {
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            CustomProgress.close();
            FileUtil.clearDir(FileUtil.getTempFile());
            Log.i("juner", "juner  error.getMessage(): " + error.getMessage());

        }
    };

    private void doPublish(){
        RequestManager.getInstance().call(new SaveCommentApi(
                new SaveCommentApi.SaveCommentParams(StringUtil.getListString(netPhotos),response.getValue("ORDER_ID"),
                        mRbskill.getRating()+"",mRbservice.getRating()+"",mRbspeed.getRating()+"" ,mEtRemark.getText().toString()), respOrderHandleListener, errorListener));
        CustomProgress.show(ShuiGCommentActivity.this,"正在提交...",true,null);
    }

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        ninePhotoLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<File> files = ImageUtils.makePaths2ImgFileList(netPhotos);
                netPhotos.clear();
                CustomProgress.show(ShuiGCommentActivity.this, "正在上传...", true, null);
                PushImgApi p = new PushImgApi(respWorkersListener, errorListener, "files", files, null);
                RequestManager.getInstance().call(p);
            }
        },100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            ninePhotoLayout.setData(BGAPhotoPickerActivity.getSelectedImages(data));
            mIvPub.setVisibility(View.GONE);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            ninePhotoLayout.setData(BGAPhotoPickerPreviewActivity.getSelectedImages(data));
        }
    }


    @Override
    public void initView() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        titleBar.setTitle("立即评论");
        response = new ARResponse(getIntent().getStringExtra("response"));
        ninePhotoLayout = (BGASortableNinePhotoLayout) findViewById(R.id.activity_discover_invest_publish_nine_photo);
        ninePhotoLayout.init(ShuiGCommentActivity.this);
        ninePhotoLayout.setDelegate(ShuiGCommentActivity.this);

    }



    @Override
    public boolean hasTitleBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_comment;
    }


    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "ZhongCDownload");

            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 9, ninePhotoLayout.getData()), REQUEST_CODE_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        ninePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, MAX_PHOTO_COUNT, models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
    }
}
